import {
  completeEnergyData,
} from '../components'
import type {
  EnergyDataItem,
} from '../components/type'
import type { ViewChartPieProps } from '@/components/view-chart-pie/type'
import { statisticalAnalysisApi } from '@/api'

export function useQueryLists() {
  const [energyTypes, setEnergyTypes] = useShallowState<
    any[]
  >([])
  const [energyOverview, setEnergyOverview]
    = useShallowState<any[]>([])
  const [energyData, setEnergyData] = useShallowState<
    EnergyDataItem[]
  >([])

  const tabsData = computed(() => {
    // const all = unref(energyTypes);
    // const target = unref(energyOverview);
    // const o = target.map(item => {
    //   if (!item.energyId) {
    //     return {
    //       type: ENERGY_COMPREHENSIVE,
    //       title: '综合能耗',
    //       unit: '吨标准煤',
    //       /**同比 */
    //       yoy:
    //         item.energyCompanyConsumePercentage?.toString() ??
    //         '',
    //       /**环比 */
    //       qoq:
    //         item.energyChainConsumePercentage?.toString() ??
    //         '',
    //       value: item.energyConsume
    //     };
    //   }
    //   const c = all.find(v => v.id === item.energyId);
    //   if (!c) return undefined;
    //   return {
    //     type: c.id.toString(),
    //     title: c.name,
    //     unit: c.energyUnit,
    //     /**同比 */
    //     yoy:
    //       item.energyCompanyConsumePercentage?.toString() ??
    //       '',
    //     /**环比 */
    //     qoq:
    //       item.energyChainConsumePercentage?.toString() ??
    //       '',
    //     value: item.energyConsume
    //   };
    // });

    // return o.filter(v =>
    //   Boolean(v)
    // ) as StatisticsDataItem[];
    return unref(energyTypes)
  })

  const x = computed(() => {
    return unref(energyData).map(v => v.name)
  })
  const l = computed(() => {
    const d = unref(energyData)
    return d.length > 0
      ? d[0]?.data.map(v => v.key) ?? []
      : []
  })
  const y = computed(() => {
    const r = unref(x).length
    const c = unref(l)?.length ?? 0
    const d = unref(energyData).reduce((acc, v) => {
      acc = acc.concat(v.data.map(vv => vv.value))
      return acc
    }, [] as EnergyDataItem['data'][number]['value'][])
    return Array.from({ length: r }).map((_m, i) => {
      return Array.from({ length: c }).map(
        (_n, j) => d[i * c + j]!,
      )
    })
  })

  const columns = computed(() => {
    return ['班组', ...unref(l), '合计']
  })
  const tableData = computed(() => {
    const d = unref(x)
    return unref(y).map((v, i) => {
      return [
        d[i],
        ...v,
        +(
          v.reduce(
            (a, b) => (Number(a) || 0) + (Number(b) || 0),
            0,
          ) as number
        ).toFixed(2),
      ]
    })
  })

  const pieData = computed(() => {
    const d = unref(tableData)
    return (
      d.length > 0
        ? {
            source: [
              ['班组能耗占比', '能耗量'],
              ...d.map(v => [v[0], v[v.length - 1]]),
            ],
          }
        : {
            source: [],
          }
    ) as ViewChartPieProps['dataset']
  })

  const emptyPie = computed(() => {
    const s = unref(pieData)?.source as any[]
    return s.length === 0 || s.slice(1).every(v => +v[1] === 0)
  })

  async function getEnergyTypes(params: {
    pointId: number
    type: number
    dataTime: string
  }) {
    try {
      const { data }
        = await statisticalAnalysisApi.selectPointEnergyType2(
          params,
        )

      // 2024-06-20 修改能源品种（从数据源配置获取）
      const result = (data || []).map((v: any) => {
        return {
          // StatisticsTabs 组件的 active，不用 indicatorNumber
          // 是因为 数据源配置中有可能没有配置 indicatorNumber
          type: v.name,
          indicatorNumber: v.value,
          title: v.name,
          unit: null,
          /** 同比 */
          yoy: v.yoy,
          /** 环比 */
          qoq: v.mom,
          value: v.now,
        }
      })
      setEnergyTypes(result)
    }
    catch (e) {}
  }
  async function getEnergyOverview(params: {
    pointId: number
    dataTime: string
    type: number
  }) {
    const { data }
      = await statisticalAnalysisApi.selectPointEnergyConsumeSum(
        params,
      )
    setEnergyOverview(data || [])
  }
  async function getEnergyData(params: {
    pointId?: number
    type: number
    dataTime: string
    energyId?: number
    indicatorNumber: string
  }) {
    setEnergyData([])
    try {
      const { data: shiftList } = await statisticalAnalysisApi.selectShiftList(params.dataTime)
      const { data }
        = await statisticalAnalysisApi.selectTeamPointEnergyConsumeList(
          params,
        )

      /** 按班次顺序 补全数据 */
      data.forEach((v: any) => {
        const dataList = v.dataList || []
        v.dataList = shiftList.map((vv) => {
          return {
            key: vv,
            val: dataList.find((vvv: any) => vvv.key === vv)?.val,
          }
        })
      })
      // console.log('data: ', data);
      setEnergyData(
        completeEnergyData(data || [], 'teamName'),
      )
    }
    catch (e) {}
  }

  function findIndicatorNumber(energyType: string) {
    return unref(energyTypes).find(item => item.type === energyType)?.indicatorNumber
  }

  return {
    /** 能源类型列表 */
    energyTypes,
    /** 能源概览列表 */
    energyOverview,
    /** 能源数据列表 */
    energyData,

    /** 能源类型选项卡数据 */
    tabsData,
    emptyPie,

    /** 能源数据表格表头 */
    columns,
    /** 能源数据列表表格数据 */
    tableData,

    /** 堆叠图x轴数据 */
    x,
    /** 堆叠图y轴数据 */
    y,
    /** legend 数据列 */
    l,
    /** pie图数据列 */
    pieData,

    /** 获取能源类型列表 */
    getEnergyTypes,
    /** 获取能源概览列表 */
    getEnergyOverview,
    /** 获取能源数据列表 */
    getEnergyData,
    /** 设置能源类型列表 */
    setEnergyTypes,
    /** 设置能源概览列表 */
    setEnergyOverview,
    /** 设置能源数据列表 */
    setEnergyData,
    findIndicatorNumber,
  }
}
